<template>
  <el-link @click="router.push('/home')" :underline="false" class="back-link">
    <el-icon style="vertical-align: middle; font-size: 28px"><ArrowLeft /></el-icon>
    <span style="vertical-align: middle; font-size: 25px">返回</span>
  </el-link>
  <el-form :model="form" label-width="80px">
    <el-form-item label="收件人" :error="receiverError" :class="{ 'is-error': receiverError }">
      <el-input
        v-model="form.receiver"
        @blur="validateReceiver"
        placeholder="请输入收件人ID或邮箱"
      />
    </el-form-item>
    <el-form-item label="抄送">
      <el-input v-model="form.cc" placeholder="多个用逗号分隔" />
    </el-form-item>
    <el-form-item label="主题">
      <el-input v-model="form.subject" />
    </el-form-item>
    <el-form-item label="正文">
      <el-input type="textarea" v-model="form.content" rows="25" />
    </el-form-item>
    <!-- 附件上传 -->
    <div>
      <input type="file" ref="fileInput" style="margin-right: 12px" />
      <el-button
        type="primary"
        @click="uploadAttach"
        style="background-color: #ff8585; border: none"
        >上传附件</el-button
      >
    </div>
    <el-form-item>
      <el-button
        type="primary"
        @click="updateDraft"
        :loading="loading"
        style="background-color: #ccc; border: none"
        >保存草稿</el-button
      >
      <el-button
        type="success"
        @click="sendDraft"
        :loading="loading"
        style="background-color: #ff8585; border: none"
        >发送</el-button
      >
    </el-form-item>

    <!-- 展示附件列表 -->
    <li v-for="attachment in form.attachments" :key="attachment.id">
      <div>
        <span>{{ attachment.file_name }}</span>
        <el-button type="danger" @click="deleteAttachment(attachment.id)">删除</el-button>
      </div>
    </li>
  </el-form>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMailDetailAPI, updateDraftAPI, sendDraftAPI } from '@/api/mailsAPI'
import { ElMessage } from 'element-plus'
import { type AttachListItem, deleteAttachmentAPI } from '@/api/attachAPI'
import { ArrowLeft } from '@element-plus/icons-vue'
// import AttachmentManager from '@/components/AttachmentManager.vue'
// import TestAttach from '@/components/attachment/UploadAttach.vue'

// import AttachList from '@/components/attachment/AttachList.vue'
import axios from 'axios'
import { BASEURL } from '@/api/http'

//  路由参数
const route = useRoute()
const router = useRouter()
const loading = ref(false) //加载中
// 草稿id
const draftId = ref<number | null>(route.params.draftId ? Number(route.params.draftId) : null)
//  表单数据
const form = ref({
  receiver: '',
  cc: '',
  subject: '',
  content: '',
  attachments: [] as AttachListItem[],
})
//附件上传
const fileInput = ref<HTMLInputElement>()
//加载草稿
const fetchDraft = async () => {
  // 只有有draftId时才去请求
  if (!draftId.value) return
  const res = await getMailDetailAPI(draftId.value)
  console.log(res)

  if (res.code === 200) {
    form.value.receiver = res.data.receiver
    form.value.subject = res.data.subject
    form.value.content = res.data.body
    form.value.attachments = res.data.attachments
    form.value.cc = res.data.cc.join(',')
  } else {
    ElMessage.error('获取草稿失败')
    router.push('/draft')
  }
}
//校验
const receiverError = ref('')
const receiverValid = ref(true)

const validateReceiver = () => {
  const value = form.value.receiver.trim()
  const idReg = /^[a-z0-9]+$/
  const emailReg = /^[a-z0-9]+@[a-z0-9]+\.com$/
  receiverValid.value = idReg.test(value) || emailReg.test(value)
  if (!receiverValid.value) {
    receiverError.value = '请输入正确的收件人ID或邮箱地址'
  } else {
    receiverError.value = ''
  }
}
//上传附件
//API
const uploadAttachmentAPI = async (): Promise<AttachListItem> => {
  const formData = new FormData()
  const id = localStorage.getItem('id') || ''
  const token = localStorage.getItem('token') || ''
  formData.append('file', fileInput.value!.files![0])
  formData.append('email_id', String(draftId.value))
  try {
    const response = await axios.post(BASEURL + '/attach/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        id: id,
        token: token,
      },
    })
    if (response.data && response.data.data) {
      ElMessage.success('上传附件成功,已为您自动保存')
      return response.data.data as AttachListItem
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    ElMessage.error('更新草稿失败' + error)
    throw error
  }
}

//按钮点击事件
const uploadAttach = async () => {
  const file = fileInput.value?.files?.[0]
  if (!file) {
    ElMessage.error('请选择文件')
    return
  }
  // 文件大小限制：500MB
  const maxSize = 500 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过500MB')
    return
  }
  try {
    const res = await uploadAttachmentAPI()
    if (res) {
      form.value.attachments.push(res)
    }
  } catch (e) {
    // 已有错误提示，无需处理
    console.error(e)
  }
}

//删除附件按钮
const deleteAttachment = async (attachment_id: number) => {
  try {
    console.log(attachment_id)
    console.log(draftId.value)
    console.log(localStorage.getItem('token'))

    const res = await deleteAttachmentAPI({ attachment_id })
    if (res.code === 200) {
      ElMessage.success('删除成功')
      form.value.attachments = form.value.attachments.filter((item) => item.id !== attachment_id)
    }
  } catch (e) {
    ElMessage.error('删除附件失败' + e)
  }
}

//  更新草稿
const updateDraft = async () => {
  loading.value = true
  // validateReceiver()
  // if (!receiverValid.value) {
  //   loading.value = false
  //   return
  // }
  try {
    if (!draftId.value) {
      ElMessage.error('请先保存为草稿')
      return
    }
    console.log(localStorage.getItem('token'))

    const res = await updateDraftAPI(draftId.value, {
      receiver: form.value.receiver,
      cc: form.value.cc
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
      subject: form.value.subject,
      content: form.value.content,
      attachments: form.value.attachments.map((item) => {
        return item.id
      }), //把id给他
    })
    if (res.code === 200) {
      ElMessage.success('草稿已更新')
    } else {
      ElMessage.error(res.msg)
      console.log(res)
    }
  } catch (e) {
    ElMessage.error('更新草稿失败' + e)
    console.log(e)
  } finally {
    loading.value = false
  }
}

const sendDraft = async () => {
  loading.value = true
  validateReceiver()
  if (!receiverValid.value) {
    loading.value = false
    return
  }
  try {
    if (!draftId.value) {
      ElMessage.error('请先保存为草稿')
      return
    }
    await updateDraft()
    const res = await sendDraftAPI(draftId.value)
    if (res.code === 200) {
      ElMessage.success('发送成功')
      router.push('/sent')
    } else {
      ElMessage.error(res.msg)
      console.log(res)
    }
  } catch (e) {
    ElMessage.error('发送失败' + e)
    console.log(e)
  } finally {
    loading.value = false
  }
}

onMounted(fetchDraft)
</script>

<style scoped>
.back-link .el-icon {
  margin-right: 4px;
  font-size: 18px;
  margin-bottom: 20px;
}
.back-link span {
  margin-right: 4px;
  font-size: 18px;
  margin-bottom: 20px;
}
.back-link:hover {
  color: #d16053;
}
</style>
